<template>
  <div class="active">
    <Form
      :label-width="118"
      :model="formData"
      ref="formItem"
      :rules="infoRules"
    >
      <Row :gutter="48">
        <i-col span="16">
          <FormItem label="活动名称" prop="name">
            <Input
              placeholder="请输入活动名称"
              clearable
              v-model="formData.name"
            />
          </FormItem>
          
          <FormItem label="活动内容" prop="content">
            <ckeditor
              :editor="editor"
              v-model="formData.content"
              :config="editorConfig"
            ></ckeditor>
          </FormItem>
        </i-col>
        <i-col span="8">
          <FormItem label="形象图" prop="banner" :label-width="80">
            <div v-if="formData.banner">
              <img :src="formData.banner" width="100" height="100" />
            </div>
            <div class="imageUpdate">
              <Upload
                ref="upload"
                name="file"
                :show-upload-list="false"
                :on-success="handleSuccess"
                :format="['jpg', 'jpeg', 'png']"
                :action="requestAction"
                :before-upload="handleBefore"
              >
                <div>
                  <Button
                    type="primary"
                    class="ivu-mr-8"
                    size="small"
                    :loading="loading"
                  >
                    {{ loading ? "上传中..." : "上传" }}
                  </Button>
                </div>
              </Upload>
              <Button type="success" size="small" @click="showImgModal = true"
                >选择</Button
              >
            </div>
          </FormItem>
          <FormItem label="活动时间" prop="TimeRanges" :label-width="80">
            <DatePicker
              type="daterange"
              v-model="formData.TimeRanges"
              format="yyyy-MM-dd"
              placeholder="请选择活动日期"
              style="width: 100%"
              @on-change="timeChange"
            />
          </FormItem>
          <FormItem label="标签" prop="model1" :label-width="80">
            <Select
              v-model="formData.model1"
              filterable
              multiple
              allow-create
              @on-change="selectTag"
              @on-create="handleCreate"
            >
              <Option
                v-for="item in tagList"
                :value="+item.value"
                :key="item.value"
                :disabled="+item.disabled === 1 ? false : true"
                >{{ item.label }}</Option
              >
            </Select>
          </FormItem>
          <FormItem label="视频ID" prop="video_id" :label-width="80">
            <Input
              placeholder="请输入视频ID,视频ID从视频后台获取"
              v-model="formData.video_id"
            />
          </FormItem>
          <FormItem
            label="视频封面"
            prop="cover_img"
            :label-width="80"
            :rules="
              formData.video_id
                ? [{ required: true, message: '请选择视频封面', trigger: 'bulr' }]
                : infoRules.cover_img
            "
          >
            <div v-if="formData.cover_img" class="demo-upload-list">
              <img :src="formData.cover_img" width="100" height="100" />
              <div class="demo-upload-list-cover">
                <Icon
                  type="ios-trash-outline"
                  @click="formData.cover_img = ''"
                ></Icon>
              </div>
            </div>
            <div class="imageUpdate">
              <Upload
                ref="upload"
                name="file"
                :show-upload-list="false"
                :on-success="handleSuccess1"
                :format="['jpg', 'jpeg', 'png']"
                :action="requestAction"
                :before-upload="handleBefore1"
              >
                <div>
                  <Button
                    type="primary"
                    class="ivu-mr-8"
                    size="small"
                    :loading="loading1"
                  >
                    {{ loading1 ? "上传中..." : "上传" }}
                  </Button>
                </div>
              </Upload>
              <Button type="success" size="small" @click="showImgModal1 = true"
                >选择</Button
              >
            </div>
          </FormItem>
          <FormItem label="排序" prop="sort" class="ivu-inline-block" :label-width="80">
            <InputNumber v-model="formData.sort" :min="0" />
          </FormItem>
          <FormItem label="关注" prop="sub_config_num" class="ivu-inline-block" :label-width="80">
            <InputNumber v-model="formData.sub_config_num" :min="0" />
          </FormItem>
          <FormItem label="首页推荐" prop="recommend_type" :label-width="80">
            <Switch v-model="formData.recommend_type" />
          </FormItem>
        </i-col>
      </Row>
    </Form>
    <!-- 全局选图片组件 -->
    <glo-check v-model="showImgModal" @getImgArr="changeAvatar" />
    <glo-check v-model="showImgModal1" @getImgArr="changeAvatar1" />
  </div>
</template>
<script>
import { updatefileTemp } from "@/api/set.js";
import ClassicEditor from "@ckeditor/ckeditor5-build-classic";
import CKEditor from "@ckeditor/ckeditor5-vue";
const ckUpload = require("../../../libs/ckeditorUplodImg5");
import { addActive, updateActive, activeDetial } from "@/api/jzy.js";
import Setting from "@/setting";
import util from "@/libs/util";
import { Message } from "view-ui-plus";
export default {
  name: "modalName",
  components: { ckeditor: CKEditor.component },
  props: ["editorType", "activeInfo", "articleModal"],
  data() {
    return {
      loading: false,
      loading1: false,
      showImgModal: false, //是否展示图片选择模态框
      showImgModal1: false,
      baseUrl: Setting.request.apiBaseURL,
      requestAction: "",
      editor: ClassicEditor,
      editorConfig: {
        extraPlugins: [ckUpload.MyCustomUploadAdapterPlugin],
        fullscreen: {
          // 点击按钮后会执行的回调函数
          handler: () => {
            // this.modalstatus = true;
          },
        },
        material: {
          // 点击按钮后会执行的回调函数
          handler: (e) => {
            this.askData();
            this.modalstatus = true;
            this.showlink = true;
            this.img = "";
            this.isDobule = true;
          },
        },
        mediaEmbed: {
          providers: [
            {
              name: "myprovider",
              url: [/^lizzy.*\.com.*\/media\/(\w+)/, /^www\.lizzy.*/, /^.*/],
              html: (match) => {
                //获取媒体url
                const input = match["input"];
                //console.log('input' + match['input']);
                return (
                  '<div style="position: relative; padding-bottom: 100%; height: 0; padding-bottom: 70%;">' +
                  `<iframe src="${input}" ` +
                  'style="position: absolute; width: 100%; height: 100%; top: 0; left: 0;" ' +
                  'frameborder="0" allowtransparency="true" allow="encrypted-media">' +
                  "</iframe>" +
                  "</div>"
                );
              },
            },
          ],
        },
      },
      initTagList: [],
      tagList: [],
      model1: [],
      formData: {
        name: "",
        banner: "",
        start_time: "",
        end_time: "",
        tag: [],
        TimeRanges: [],
        content: "",
        sort: 1,
        model1: [],
        sub_config_num: "",
        recommend_type: false,
        cover_img: "",
        video_id: "",
      },
      infoRules: {
        name: [
          { required: true, message: "请输入活动名称", trigger: "bulr" },
          { trigger: "bulr", validator: this.watermarkContentVaild },
        ],
        banner: [{ required: true, message: "请上传形象图", trigger: "bulr" }],
        TimeRanges: [
          {
            type: "array",
            required: true,
            fields: {
              0: { type: "date", required: true, message: "请选择起止日期" },
              1: { type: "date", required: true, message: "请选择起止日期" },
            },
          },
        ],
        content: [
          { required: true, message: "请输入活动内容", trigger: "bulr" },
        ],
        model1: [
          {
            type: "array",
            required: true,
            message: "请选择Tag",
            trigger: "change",
          },
        ],
        cover_img: [{ required: false, trigger: "bulr" }],
      },
    };
  },
  methods: {
    // 刷新模态框内form的事件
    resetForm() {
      this.$refs.formItem.resetFields();
    },
    watermarkContentVaild(rule, value, callback) {
      let length = value.replace(/[^\x00-\xff]/g, "01").length;
      if (length > 36) {
        callback(new Error("请输入1~18个汉字"));
      } else {
        callback();
      }
    },
    handleBefore() {
      this.loading = true;
    },
    // 图片上传改变形象图的函数
    handleSuccess(response, file, fileList) {
      this.formData.banner = `${response.data.host}${response.data.image_url[0]}`;
      this.loading = false;
      const id = response.data.image_id[0];
      updatefileTemp({ id });
    },
    handleBefore1() {
      this.loading1 = true;
    },
    // 图片上传改变形象图的函数
    handleSuccess1(response, file, fileList) {
      this.formData.cover_img = `${response.data.host}${response.data.image_url[0]}`;
      this.loading = false;
      const id = response.data.image_id[0];
      updatefileTemp({ id });
    },
    // 自我选择改变形象图的函数
    changeAvatar(arr) {
      this.formData.banner = arr[0];
    },
    changeAvatar1(arr) {
      this.formData.cover_img = arr[0];
    },
    timeChange(e) {
      this.formData.start_time = e[0];
      this.formData.end_time = e[1];
      this.formData.TimeRanges = e;
    },
    handleCreate(e) {
      if (e.trim().length < 1) {
        this.$Message["warning"]("标签不能为空");
        return;
      } else if (e.length > 6) {
        this.$Message["warning"]("标签长度不能超过6");
        return;
      } else {
        let add = true;
        this.tagList.forEach((item) => {
          if (item.label == e) {
            add = false;
            return;
          }
        });
        if (add) {
          var id = new Date().getTime();
          this.tagList.push({
            value: id,
            label: e,
            disabled: "1",
          });
        }
      }
    },
    selectTag(e) {
      this.tagList.forEach((item) => {
        if (e[e.length - 1] == item.label) {
          if (e.includes(+item.value)) {
            e.pop();
          } else {
            e[e.length - 1] = +item.value;
          }
        }
      });
      if (
        e.length &&
        (e[e.length - 1].length > 6 ||
          e[e.length - 1].toString().trim().length < 1)
      ) {
        e.pop();
        return;
      }
      if (e.length > 3) {
        this.$Message.warning("标签不能超过三个~");
        e.splice(3, 1);
        return;
      }
    },
    saveData() {
      this.$refs["formItem"].validate((valid) => {
        if (valid) {
          this.formData.tag = [];
          this.formData.model1.forEach((item) => {
            let flag = true,
              add = true;
            this.initTagList.forEach((ele) => {
              if (+ele.value == +item) {
                this.formData.tag.push({ id: item, name: ele.label });
                flag = false;
                add = false;
              }
            });
            if (flag) {
              this.tagList.forEach((ele) => {
                if (+ele.value == +item) {
                  this.formData.tag.push({ id: 0, name: ele.label });
                  flag = true;
                  add = false;
                }
              });
              if (add) {
                this.formData.tag.push({ id: 0, name: item });
              }
            }
          });
          let params = {
            name: this.formData.name,
            banner: this.formData.banner,
            start_time: this.formData.start_time,
            end_time: this.formData.end_time,
            tag: this.formData.tag,
            content: this.formData.content,
            sort: this.formData.sort,
            sub_config_num: this.formData.sub_config_num,
            recommend_type: this.formData.recommend_type ? 1 : 2,
            cover_img: this.formData.cover_img,
            video_id: this.formData.video_id,
          };
          if (this.editorType) {
            addActive(params).then((res) => {
              this.$emit("refresh", false);
            });
          } else {
            params.id = this.activeInfo.id;
            updateActive(params).then((res) => {
              this.$emit("refresh", false);
            });
          }
          activeDetial({ id: "0" }).then((res) => {
            this.initTagList = [...res.condition.tag_list];
            this.tagList = res.condition.tag_list;
          });
        }
      });
    },
  },
  watch: {
    articleModal() {
      if (this.articleModal) {
        if (this.activeInfo.id) {
          activeDetial({ id: this.activeInfo.id }).then((res) => {
            this.formData = {
              name: res.name,
              banner: res.banner,
              start_time: res.start_time,
              end_time: res.end_time,
              tag: [],
              TimeRanges: [res.start_time, res.end_time],
              content: res.content,
              sort: res.sort,
              model1: res.tag_ids,
              sub_config_num: res.sub_config_num,
              recommend_type: res.recommend_type == 1 ? true : false,
              cover_img: res.cover_img,
              video_id: res.video_id,
            };
            this.initTagList = [...res.condition.tag_list];
            this.tagList = res.condition.tag_list;
          });
        } else {
          (this.formData = {
            name: "",
            banner: "",
            start_time: "",
            end_time: "",
            tag: [],
            TimeRanges: [],
            content: "",
            sort: 1,
            model1: [],
            sub_config_num: "",
            recommend_type: false,
            cover_img: "",
            video_id: "",
          }),
            activeDetial({ id: "0" }).then((res) => {
              this.initTagList = [...res.condition.tag_list];
              this.tagList = res.condition.tag_list;
            });
        }
      }
    },
  },
  mounted() {
    this.requestAction =
      this.baseUrl +
      `/v1/upload/images?auth_access_token=${util.cookies.get(
        "token"
      )}&auth_project_id=${localStorage.getItem('currentProject')}`;
  },
};
</script>
<style lang='less' scoped>
.ivu-modal {
  top: 50px;
}
.imageUpdate {
  display: flex;
}
.imageUpdate button {
  vertical-align: top;
}
/deep/ .ck.ck-editor__main > .ck-editor__editable {
  height: 450px;
}
.active {
  padding-bottom: 20px;
}
.demo-upload-list {
  display: inline-block;
  width: 100px;
  height: 100px;
  text-align: center;
  line-height: 100px;
  border: 1px solid transparent;
  border-radius: 4px;
  overflow: hidden;
  background: #fff;
  position: relative;
  box-shadow: 0 1px 1px rgba(0, 0, 0, 0.2);
  margin-right: 4px;
}
.demo-upload-list img {
  width: 100%;
  height: 100%;
}
.demo-upload-list-cover {
  display: none;
  position: absolute;
  top: 0;
  bottom: 0;
  left: 0;
  right: 0;
  background: rgba(0, 0, 0, 0.6);
}
.demo-upload-list:hover .demo-upload-list-cover {
  display: block;
}
.demo-upload-list-cover i {
  color: #fff;
  font-size: 20px;
  cursor: pointer;
  margin: 0 2px;
}
</style>